<!--
  文件描述：流程图-单个条件组件
-->
<template>
  <div class="condition-item-col flex-method">
    <div class="condition-node flex-method">
      <!--   模块内容   -->
      <div class="condition-node-box" @click="open()">
        <div class="title">
          <span class="title-left ellipsis-text">条件</span>
          <el-icon size="20" class="title-right" @click="deleMe"
            :style="{ display: processData.nodeType == '0' || disabled ? 'none' : '' }">
            <Close />
          </el-icon>
        </div>
        <div class="dec ellipsis-text">
          {{ processData.nodeNm }}
        </div>
      </div>
      <!--  按钮以及线  -->
      <addNodeBtn :process-data="processData" :disabled="disabled" />
    </div>
    <template v-if="processData.childNode">
      <process-page-item :process-data="processData" :disabled="disabled" />
    </template>
    <template v-if="frist">
      <div class="top-left-cover-line cover-line"></div>
      <div class="bottom-left-cover-line cover-line"></div>
    </template>
    <template v-if="last">
      <div class="top-right-cover-line cover-line"></div>
      <div class="bottom-right-cover-line cover-line"></div>
    </template>
    <el-drawer v-model="drawer" title="条件配置" append-to-body :size="$isMobile() ? '80%' : '30%'">
      <el-form label-width="auto" :disabled="disabled" :model="_processData" :rules="rules" ref="ruleFormRef">
        <el-form-item label="条件名称：" prop="nodeNm">
          <el-input clearable v-model="_processData.nodeNm" placeholder="请输入条件名称" style="width: 200px;" />
        </el-form-item>
      </el-form>
      <div class="fun" style="text-align: right; margin-bottom: 10px;">
        <el-button :disabled="disabled" type="primary" plain
          @click="_processData.nodeConditions.push({ ...singleData })">添加条件</el-button>
      </div>
      <div class="table">
        <el-table border empty-text="暂无数据" :data="_processData.nodeConditions"
          :header-cell-style="{ background: 'var(--table-title-color)', color: 'var(--table-title-font-color)' }">
          <el-table-column prop="fieldCnNm" label="条件" min-width="150">
            <template #default="{ row }">
              <el-select :disabled="disabled" clearable filterable v-model="row.conditionId" placeholder="请选择条件"
                size="small" @change="changeCondition(row)">
                <el-option v-for="item in (row.conditionOptions || [])" :key="item.id" :label="item.fieldCnNm"
                  :value="item.id" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="comparison" label="比较运算符" min-width="150">
            <template #default="{ row }">
              <el-select :disabled="disabled" clearable v-model="row.comparison" placeholder="请选择比较运算符">
                <el-option :label="item" :value="item" v-for="(item, index) in row.comparisonList" :key="index" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="conditionValue" label="条件值" min-width="150">
            <template #default="{ row }">
              <el-input :disabled="disabled" clearable v-model="row.conditionValue" placeholder="请输入条件值">
                <template #append>
                  {{ row.unit }}
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column :fixed="$isMobile() ? false : 'right'" label="操作" width="80">
            <template #default="scope">
              <el-button :disabled="disabled" text type="primary" size="small"
                @click="_processData.nodeConditions.splice(scope.$index, 1)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="font-size: 14px;color: var(--table-title-font-color);">
        注：当审批单同时满足以上条件时进入此流程
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="save()">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script setup name="conditionItemCol">
import { ref, inject } from 'vue'
import api from "@/api"
import { ElMessage } from "element-plus";
import { getCacheWithExpiry, setCacheWithExpiry } from "@/utils/busi"
import addNodeBtn from '@/view/workflow/config/components/comp/add-node-btn.vue'
import processPageItem from '@/view/workflow/config/components/processPageItem.vue'
const props = defineProps(['processData', 'frist', 'last', 'disabled'])

const drawer = ref(false)
const deleData = inject('deleData')
const deleMe = () => {
  deleData?.({
    type: '3', // 具体条件
    nodeId: props.processData.nodeId
  })
}
const singleData = {
  conditionId: '',// 流程条件ID
  comparison: '', // 比较运算符
  conditionValue: '', // 流程条件值
  conditionOptions: []
}
const rules = ref({
  nodeNm: [
    { required: true, message: '请输入节点名称', trigger: 'blur' },
  ]
})
const _processData = ref({})
const ruleFormRef = ref()

const open = async () => {
  _processData.value = JSON.parse(JSON.stringify(props.processData))
  let conditionOptions = getCacheWithExpiry('wfConditionOptions')
  if (!conditionOptions) {
    conditionOptions = await getConditionOptions()
    setCacheWithExpiry('wfConditionOptions', conditionOptions, 600000)
  }
  singleData['conditionOptions'] = conditionOptions
  if (_processData.value.nodeConditions) {
    _processData.value.nodeConditions.forEach(item => {
      item.conditionOptions = conditionOptions
      const conditionOption = conditionOptions.find(conditionOption => item.conditionId === conditionOption.id) || {}
      item.unit = conditionOption.unit
    });
  }
  drawer.value = true
}
const getConditionOptions = async () => {
  const res = await api.get('/workflow/condition/pageList', { pageNum: 1, pageSize: 999 })
  if (res.data.code === 200) {
    return res.data.data.records
  } else {
    ElMessage.error(res.data.msg)
    return null
  }
}

const changeCondition = (row) => {
  row.comparison = null
  row.conditionValue = null
  const condition = row.conditionOptions.find((item) => row.conditionId === item.id) || {}
  row.comparisonList = condition.comparisons.split(',') || []
  row.unit = condition.unit
}

const save = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      validateTable()
      props.processData.nodeNm = _processData.value.nodeNm
      props.processData.nodeConditions = _processData.value.nodeConditions
      drawer.value = false
    }
  })
}

const validateTable = () => {
  if (_processData.value.nodeConditions && _processData.value.nodeConditions.length > 0) {
    _processData.value.nodeConditions.forEach((item, index) => {
      if (!item.conditionId || !item.comparison || !item.conditionValue) {
        ElMessage.warning(`请把第${index + 1}行条件填写完整!`)
        throw new Error()
      }
    })
  } else {
    ElMessage.warning(`条件不能为空!`)
    throw new Error()
  }
}


</script>
<style scoped lang="less">
@import '@/view/workflow/config/components/index.less';
</style>